<template>
    <div>
        <!-- <el-form label-width="110px" size="small">
            <el-col class="form-row"> -->
        <el-form-item label="价格模式:" v-if="!notShowPriceType">
            <el-select v-model="form.orderPriceType" size="mini" disabled>
                <el-option v-for="i in investPriceSelectData" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                </el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="当前市价:" :class="['font-color-' + textColor]" class="icon-form-item">
            <el-input v-model="calcPrice" disabled>
                <template slot="append">元</template>
            </el-input>
            <i v-if="!notShowPriceType" class="el-icon-refresh-right" @click="getCalcPrice('1')"></i>
        </el-form-item>
        <el-form-item label="指令价格:">
            <RiskInputNumber
                :disabled="!checkPermission('B_325')"
                :input="form.orderPrice"
                :inputAfter="'元'"
                :colorStyle="textColor"
                :precision="2"
                :maxlength="10"
                :field="'orderPrice'"
                @getInputNumber="getInputNumber(arguments)"
            >
            </RiskInputNumber>
        </el-form-item>
        <el-form-item label="指令数量:">
            <RiskInputNumber
                :readonly="!stockCode"
                :input="form.orderAmount"
                :inputAfter="'张'"
                :colorStyle="textColor"
                :maxlength="9"
                :precision="2"
                :disabled="targetType == '2'"
                :field="'orderAmount'"
                @getInputNumber="getInputNumber(arguments)"
            >
            </RiskInputNumber>
        </el-form-item>

        <el-form-item label="指令金额:">
            <RiskInputNumber
                :input="form.orderBalance"
                :inputAfter="'元'"
                :colorStyle="textColor"
                :precision="2"
                :field="'orderBalance'"
                :disabled="targetType == '1'"
                @getInputNumber="getInputNumber(arguments)"
            >
            </RiskInputNumber>
        </el-form-item>
        <!-- </el-col>
        </el-form> -->
    </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import { SGU_CACHE } from '@/utils/diction-const-util';
import { checkPermission, convertNum, handleInverseAmount, handleLimitAmount } from '@/utils/tools';
@Component({
    name: 'WarrantForm',
    components: {
        RiskInputNumber,
    },
})
// 权证指令表单
export default class WarrantForm extends Vue {
    @Prop()
    stockCode: string;
    @Prop()
    formDetail: any;
    @Prop()
    textColor: string;
    @Prop()
    notShowPriceType: boolean; // 是否显示价格模式(不同页面使用该组件用到该变量)
    @Prop()
    targetType: string; // 目标类型
    @Prop()
    stockInfo: any;
    @Prop()
    refreshNumber: number;
    @Prop()
    notMesh: boolean;
    @Prop()
    changeFlag: string;

    checkPermission = checkPermission;

    form = {
        orderPrice: '', // 指令价格
        orderAmount: '', // 指令数量
        orderBalance: '', // 指令金额
        orderPriceType: '2', // 价格模式
    };
    calcPrice: number = 0;

    orderPrice: string = '';
    investPriceSelectData: any[] = []; // 价格模式下拉数据

    @Watch('refreshNumber', { immediate: true })
    onWatchRefreshNumber() {
        if (this.refreshNumber) {
            this.getCalcPrice('2');
        }
    }

    @Watch('stockCode', { immediate: true, deep: true })
    onWatchStockCode(newValue, oldValue) {
        if (oldValue) {
            this.resetForm();
        }
        this.getCalcPrice('2');
    }

    @Watch('formDetail', { immediate: true, deep: true })
    getForm() {
        for (const key in this.formDetail) {
            this.form[key] = this.formDetail[key];
        }
        if (this.formDetail.orderPriceType === '2') {
            this.form.orderPrice = '';
            this.orderPrice = this.formDetail.orderPrice;
        }
    }

    @Watch('form', { immediate: true, deep: true })
    setForm() {
        this.$emit(
            'getForm',
            {
                orderPrice: this.orderPrice,
                orderBalance: this.form.orderBalance,
                orderAmount: this.form.orderAmount, // 指令数量
                orderPriceType: '2',
            },
            'warrantValues'
        );
        // this.$emit('getForm', this.form, 'warrantValues');
    }

    @Watch('changeFlag', { immediate: true, deep: true })
    onWatchChangeFlag() {
        if (this.form.orderAmount) {
            if (this.form.orderAmount === '0.00') {
                this.yh_message_warn('指令数量必须大于0！');
                return;
            }
            let limit = handleLimitAmount(this.changeFlag, this.stockInfo, this.form.orderAmount);
            if (!limit) {
                this.form.orderAmount = '';
            }
        }
    }

    async mounted() {
        this.investPriceSelectData = await SGU_CACHE('PriceType', '/dict/list/code/Y_000237', []);
    }

    /**
     * 获取指令价格为空时的计算价格，下面是取值顺序
     * lastPrice: 最新价
     * openPrice: 开盘价
     * closePrice: 昨收盘价
     * facePrice: 面值
     * type: 1-手动刷新(点击刷新图标)，2-自动刷新(切换证券时)
     */
    getCalcPrice(type: string) {
        if (this.stockCode) {
            this.$axios
                .post('/dataEngine/getStockPrice/' + this.stockCode)
                .then((result: any) => {
                    this.calcPrice = result;
                    if (this.form.orderPriceType == '2') {
                        this.handlePriceChange('');
                    }
                    if (type == '1') {
                        this.yh_message_success('刷新成功');
                    }
                })
                .then((result: any) => {
                    this.calcPrice = result;
                })
                .catch(() => {
                    this.calcPrice = null;
                });
        } else {
            this.calcPrice = null;
        }
    }

    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        this.form[field] = value;
        if (field == 'orderBalance') {
            this.handleOrderBalanceChange(value);
        } else if (field == 'orderAmount') {
            if (value === '0.00') {
                this.yh_message_warn('指令数量必须大于0！');
            }
            setTimeout(() => {
                // 限定指令数量
                handleLimitAmount(this.changeFlag, this.stockInfo, value);
            }, 100);
        }
    }

    // 重置表单
    resetForm() {
        this.form.orderPrice = '';
        this.form.orderAmount = '';
        this.form.orderBalance = '';
        this.form.orderPriceType = '2';
    }

    handleOrderBalanceChange(value: string) {
        if (this.form.orderPrice) {
            this.form.orderAmount = (Number(value || '0') / Number(this.form.orderPrice || '0')).toFixed(0);
        } else {
            if (this.calcPrice) {
                this.form.orderAmount = (Number(value || '0') / this.calcPrice).toFixed(0);
            }
        }

        // 反算指令数量处理
        this.form.orderAmount = handleInverseAmount(this.changeFlag, this.stockInfo, this.form.orderAmount);
    }

    handlePriceChange(value: string) {
        // // 修改指令价格
        // if (value) {
        //     // 根据输入值计算
        //     this.form.orderPriceType = '1';
        // } else {
        //     this.form.orderPriceType = '2';
        // }
        // this.calculateOrderBalance();
        // 修改指令价格
        if (value) {
            // 根据输入值计算
            this.form.orderPriceType = '1';
            this.orderPrice = this.form.orderPrice;
            if (this.targetType == '1') {
                if (this.form.orderAmount) {
                    // 绝对数量算金额
                    this.form.orderBalance = (Number(this.form.orderAmount || '0') * Number(this.orderPrice)).toFixed(2);
                    this.form.orderBalance = this.handleVerifyOrderBlance(this.form.orderBalance);
                }
            } else if (this.targetType == '2') {
                if (this.form.orderBalance) {
                    // 绝对金额反推数量
                    this.form.orderAmount = (Number(this.form.orderBalance || '0') / Number(this.orderPrice)).toFixed(0);
                    // 反算指令数量处理
                    this.form.orderAmount = handleInverseAmount(this.changeFlag, this.stockInfo, this.form.orderAmount);
                }
            }
            // this.calculateOrderBalance();
        } else {
            this.form.orderPriceType = '2';
            if (this.calcPrice) {
                this.orderPrice = this.calcPrice.toString();
                if (this.form.orderBalance) {
                    if (this.targetType == '1') {
                        // 绝对数量算金额
                        this.form.orderBalance = (Number(this.form.orderAmount || '0') * Number(this.calcPrice || '0')).toFixed(2);
                        this.form.orderBalance = this.handleVerifyOrderBlance(this.form.orderBalance);
                    } else if (this.targetType == '2') {
                        // 绝对金额反推数量
                        this.form.orderAmount = (Number(this.form.orderBalance || '0') / Number(this.calcPrice || '0')).toFixed(0);

                        this.form.orderAmount = handleInverseAmount(this.changeFlag, this.stockInfo, this.form.orderAmount);
                    }
                } else if (this.form.orderAmount) {
                    if (this.targetType == '1') {
                        this.form.orderBalance = (Number(this.form.orderAmount || '0') * Number(this.calcPrice || '0')).toFixed(2);
                        this.form.orderBalance = this.handleVerifyOrderBlance(this.form.orderBalance);
                    } else if (this.targetType == '2') {
                    }
                } else {
                    // 金额数量都是空，不做处理
                }
            }
        }
    }

    // 校验指令金额
    handleVerifyOrderBlance(orderBalance: any) {
        if (convertNum(orderBalance) === false || Number(orderBalance) > 999999999999.99) {
            this.yh_message_warn('指令金额不能超过999999999999.99!');
            orderBalance = '';
        }
        return orderBalance;
    }

    // 计算指令金额
    calculateOrderBalance() {
        // 计算指令金额
        if (this.form.orderPriceType === '1') {
            this.form.orderBalance = (Number(this.form.orderPrice || 0) * Number(this.form.orderAmount || 0)).toFixed(2);
            this.orderPrice = this.form.orderPrice;
        } else {
            this.form.orderBalance = (Number(this.calcPrice || 0) * Number(this.form.orderAmount || 0)).toFixed(2);
            // this.orderPrice = this.calcPrice.toString();
            if (this.calcPrice == null) {
                this.orderPrice = '';
            } else {
                this.orderPrice = this.calcPrice.toString();
            }
        }
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-time/styles/order-form';
</style>
